const { pool } = require("../../db");
// 封装处理函数
/**
 * 获取所有媒体信息
 * @param {number} page - 页码
 * @param {number} limit - 每页显示数量
 * @param {number} type - 类型（1：食物；2：旅行）
 * @param {string} ftype - 媒体类型（'image'：图片；'video'：视频）
 * @returns {Promise} 返回一个Promise对象，包含返回码和数据
 */
exports.getAllMedias = async (page, limit, type, ftype) => {
  const offset = (page - 1) * limit;
  const isFoodType = type == 1;
  const baseQuery = isFoodType
    ? `SELECT f.id as id, f.name as name FROM food f LIMIT ? OFFSET ?`
    : `SELECT t.id as id, t.name as name FROM travel t LIMIT ? OFFSET ?`;

  const countQuery = isFoodType
    ? `SELECT COUNT(*) as count FROM food`
    : `SELECT COUNT(*) as count FROM travel`;

  const mediaQuery = isFoodType
    ? `SELECT f.id as parentId, m.* from food f LEFT JOIN media m ON f.id=m.food_id WHERE f.id = ? and type = '${ftype}'`
    : `SELECT t.id as parentId, m.* from travel t LEFT JOIN media m ON t.id=m.travel_id WHERE t.id = ? and type = '${ftype}'`;

  try {
    // 查询总数
    const [countResult] = await pool.query(countQuery);
    const totalCount = countResult[0].count;

    // 查询基础数据
    const [dataResult] = await pool.query(baseQuery, [Number(limit), offset]);

    // 处理数据
    const processedData = await Promise.all(
      dataResult.map(async (row) => {
        const { id, name } = row;

        // 查询媒体数据
        const [mediaResult] = await pool.query(mediaQuery, [id]);

        // 处理媒体数据
        const mediaData = mediaResult.map((mediaRow) => {
          const { parentId, ...media } = mediaRow;
          return media;
        });

        return {
          id,
          name,
          media: mediaData,
        };
      })
    );

    return { code: 200, data: processedData, total: totalCount };
  } catch (error) {
    return { code: 500, msg: "服务器错误" };
  }
};
// 封装更新is_show函数
exports.updateMediaIsShow = async (id, isShow) => {
  const query = `UPDATE media SET is_show = ? WHERE id = ?`;
  try {
    await pool.query(query, [isShow, id]);
    return { code: 200, msg: "更新成功" };
  } catch (error) {
    return { code: 500, msg: "服务器错误" };
  }
};
// 删除单条media数据
exports.deleteMedia = async (id) => {
  const query = `DELETE FROM media WHERE id = ?`;
  try {
    await pool.query(query, [id]);
    return { code: 200, msg: "删除成功" };
  } catch (error) {
    return { code: 500, msg: "服务器错误" };
  }
};
